package com.example.photograph.controller;

import com.example.photograph.common.annotation.Log;
import com.example.photograph.common.enums.BusinessType;
import com.example.photograph.common.utils.poi.ExcelUtil;
import com.example.photograph.domain.*;
import com.example.photograph.page.TableDataInfo;
import com.example.photograph.service.ISysAppPhoneService;

import com.example.photograph.utils.ExcelUtils;
import com.example.photograph.utils.ShiroUtils;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author panhm
 * @date 2022-07-07
 * @Description:
 */

@Controller
@RequestMapping("/system/app")
public class SysAppPhoneController  extends BaseController{
    private String prefix = "system/app";

    @Autowired
    private ISysAppPhoneService sysAppPhoneService;

    @RequiresPermissions("system:app:view")
    @GetMapping()
    public String app()
    {
        return prefix + "/app";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysAppPhone sysAppPhone = sysAppPhoneService.selectSysAppPhoneById(id);
        mmap.put("appPhone", sysAppPhone);
        return prefix + "/detail";
    }

    /**
     * 查询套餐管理列表
     */
    @RequiresPermissions("system:app:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AppPhoneSearch appPhoneSearch)
    {


        SysAppPhone sysAppPhone = appPhoneSearch.toSysAppPhone();


        startPage();
        SysUser sysUser = ShiroUtils.getSysUser();
        if (!sysUser.isAdmin()){
            sysAppPhone.setUserId(ShiroUtils.getUserId());
        }

        List<SysAppPhone> sysAppPhones = sysAppPhoneService.selectSysAppPhoneListV1(sysAppPhone);

        List<AppPhoneDataVo> collect = sysAppPhones.stream().map(this::toAppPhoneDataVo).collect(Collectors.toList());

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(collect);
        rspData.setTotal(new PageInfo(sysAppPhones).getTotal());
        return rspData;
    }
    private AppPhoneDataVo toAppPhoneDataVo(SysAppPhone data) {
        AppPhoneDataVo appPhoneDataVo = new AppPhoneDataVo();
        appPhoneDataVo.setPhone(data.getPhone());
        long expectedTime = data.getLastUpdateTime() + 7200000L;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        appPhoneDataVo.setExpectedTime(simpleDateFormat.format(new Date(expectedTime)));
        boolean expire = System.currentTimeMillis() > expectedTime;
        appPhoneDataVo.setIsExPire(expire ? "是" : "否");
        appPhoneDataVo.setCookie(data.getCookie());
        appPhoneDataVo.setId(data.getId());
        return appPhoneDataVo;
    }
    /**
     * 新增套餐管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存套餐管理
     */
    @RequiresPermissions("system:app:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysAppPhone sysAppPhone)
    {
        return toAjax(sysAppPhoneService.insertSysAppPhone(sysAppPhone));
    }

    /**
     * 修改套餐管理
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysAppPhone sysAppPhone = sysAppPhoneService.selectSysAppPhoneById(id);
        mmap.put("SysAppPhone", sysAppPhone);
        return prefix + "/edit";
    }

    /**
     * 修改保存套餐管理
     */
    @RequiresPermissions("system:app:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysAppPhone sysAppPhone)
    {
        return toAjax(sysAppPhoneService.updateSysAppPhone(sysAppPhone));
    }

    /**
     * 删除套餐管理
     */
    @RequiresPermissions("system:app:remove")
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysAppPhoneService.deleteSysAppPhoneByIds(ids));
    }



    @PostMapping({"/getCookie"})
    @ResponseBody
    public AjaxResult getCookie(Long id) {
        return new AjaxResult(AjaxResult.Type.SUCCESS,sysAppPhoneService.getCookie(id));
    }

    @PostMapping({"/sendSms"})
    @ResponseBody
    public AjaxResult sendSms(@RequestBody SysAppPhone sysAppPhone) {
        return new AjaxResult(AjaxResult.Type.SUCCESS,sysAppPhoneService.sendSms(sysAppPhone.getPhone()));
    }

    @PostMapping({"/login"})
    @ResponseBody
    public AjaxResult login(@RequestBody LoginData loginData) {
        try {
            return new AjaxResult(AjaxResult.Type.SUCCESS,sysAppPhoneService.login(loginData));
        } catch (Exception var3) {
            return new AjaxResult(AjaxResult.Type.ERROR,var3.getMessage());
        }
    }

    /**
     * 导出就业信息管理列表
     */
    @RequiresPermissions("system:app:export")
    @Log(title = "app账号信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public com.example.photograph.common.core.domain.AjaxResult export(AppPhoneSearch appPhoneSearch)
    {
        SysAppPhone sysAppPhone = appPhoneSearch.toSysAppPhone();
        SysUser sysUser = ShiroUtils.getSysUser();
        if (!sysUser.isAdmin()){
            sysAppPhone.setUserId(ShiroUtils.getUserId());
        }
        List<AppPhoneDataVo> appPhoneDataVos = this.sysAppPhoneService.selectSysAppPhoneList(sysAppPhone);

        if (!CollectionUtils.isEmpty(appPhoneDataVos)){
            appPhoneDataVos.stream().forEach(value->{

                try {
                    String cookie = sysAppPhoneService.getCookie(value.getId());
                    value.setCookie(cookie);
                }catch (Exception e){
                    value.setCookie(e.getMessage());
                    System.out.println(e.getStackTrace().toString());
                }
            });

        }


        ExcelUtil<AppPhoneDataVo> util = new ExcelUtil<AppPhoneDataVo>(AppPhoneDataVo.class);
        return util.exportExcel(appPhoneDataVos, "app账号信息导出");
    }

    // @GetMapping({"/export"})
    // public  void export( AppPhoneSearch appPhoneSearch, HttpServletRequest request, HttpServletResponse response) throws Exception {
    //     try {
    //         SysAppPhone sysAppPhone = appPhoneSearch.toSysAppPhone();
    //
    //
    //         startPage();
    //         SysUser sysUser = ShiroUtils.getSysUser();
    //         if (!sysUser.isAdmin()){
    //             sysAppPhone.setUserId(ShiroUtils.getUserId());
    //         }
    //         List<AppPhoneDataVo> appPhoneDataVos = this.sysAppPhoneService.selectSysAppPhoneList(sysAppPhone);
    //
    //
    //         String[] headers = new String[]{"手机号", "是否超过两小时", "预计时间", "cookie"};
    //         String[] columns = new String[]{"phone", "isExPire", "expectedTime", "cookie"};
    //         appPhoneDataVos.stream().forEach(value->{
    //             String cookie = sysAppPhoneService.getCookie(value.getId());
    //             value.setCookie(cookie);
    //         });
    //         ExcelUtils.exportExcel(appPhoneDataVos, headers, columns, request, response, "登录信息.xlsx");
    //
    //     } catch (Exception var7) {
    //
    //     }
    // }

}